var layer
layui.use('layer', function () {
    layer = layer
})
var phtot_path = "../img/couphoto/"

var userId = getCookie("userid")

$.ajax({
    url: "http://localhost:8080/user/selectUCouShow",
    asyne: false,
    dataType: "json",
    type: "get",
    success: function (data) {

        let html = ''
        var list = data.data
        for (let i = 0; i < list.length; i++) {
            html += `<div class="photo"><img src="${phtot_path + data.data[i].couponMoney}.png" height="269" width="238" id="cou_${data.data[i].couponId}" class="couphoto" style="cursor:pointer"></div>
                     <div class="gap"></div>`
        }
        $(".cou_main").append(html)
    }
})

$(".cou_main").on('click', '.couphoto', function () {

    let couid = parseInt(this.id.replace(/[^0-9]/ig, ""))

    $.ajax({
        url: "http://localhost:8080/user/selectUCouHave",
        data: "userCouId=" + couid + "&userId=" + userId,
        asyne: false,
        dataType: "json",
        type: "get",
        success: function (data) {
            if (data.code === 0) {
                ureceive(couid, userId)
            } else {
                layer.msg('你已领过了嗷')
            }
        }
    })
})

function ureceive(couid, userId) {
    $.ajax({
        url: "http://localhost:8080/user/addUGetCou",
        data: "couponId=" + couid + "&userId=" + userId,
        asyne: false,
        dataType: "json",
        type: "get",
        success: function (data) {
            if (data.code === 0) {
                layer.msg('优惠券领取成功!')
            } else {
                layer.msg('网络错误，领取失败了')
            }
        }
    })
}

function getCookie(name) {
    var prefix = name + "="  // name=
    console.log(document.cookie) // name=wangwu; Hm_lvt_eaa57ca47dacb4ad4f5a2570
    // name=  第一次出现的位置
    var start = document.cookie.indexOf(prefix)
    if (start == -1) {
        return null;
    }
    // 从0+5这个位置开始，找到;第一次出现的位置，也就是这个cookie值得结束位置
    var end = document.cookie.indexOf(";", start + prefix.length)
    // name=wangwu
    // Hm_lvt_eaa57ca47dacb4ad4f5a2570;name=wangwu
    // 将字符串得总长度就是截取值得结束位置
    if (end == -1) { // 没有找到分号
        end = document.cookie.length;
    }
    var value = document.cookie.substring(start + prefix.length, end)
    return unescape(value);
}